using Microsoft.AspNetCore.Mvc;
using System.Text;
using System.Text.Json;
using static System.Net.Mime.MediaTypeNames;

namespace netCoreExample.Controllers
{
    [ApiController]
    [Route("/api/[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;
        private readonly IHttpClientFactory _httpClientFactory;

        public WeatherForecastController(ILogger<WeatherForecastController> logger, IHttpClientFactory httpClientFactory)
        {
            _logger = logger;
            _httpClientFactory = httpClientFactory;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)],
                CurrentTime = DateTime.Now
            })
            .ToArray();
        }

        [HttpGet]
        [Route("{id}")]//没约束类型会显示报错信息
        public IActionResult GetById(int id)
        {
            var data = new { Name = "张三", Age = 20, id };
            return new JsonResult(data);
        }

        [HttpGet]
        [Route("all")]//新增路由
        public IActionResult GetAll()
        {
            var data = new { Name = "张三", Age = 20 };
            return new JsonResult(data);
        }

        [HttpGet]
        [Route("{pageIndex:int}/{pageSize:int}")]//有约束类型会404，约束类型和范围按C#语法
        public IActionResult GetByPage(int pageIndex,int pageSize)
        {
            var data = new { Name = "张三", Age = 20, pageIndex, pageSize };
            return new JsonResult(data);
        }

        [HttpPost]
        public async Task<IActionResult> Post()
        {
            var jsonStr = Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)],
                CurrentTime = DateTime.Now
            })
            .ToArray();

            //get请求
            var result = String.Empty;
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://localhost:5249/WeatherForecast")
            {
                Headers = {}
            };
            var httpClient = _httpClientFactory.CreateClient();
            var httpResponseMessage = httpClient.Send(httpRequestMessage);
            if(httpResponseMessage.IsSuccessStatusCode)
            {
                result = await httpResponseMessage.Content.ReadAsStringAsync();
            }

            //序列化
            var data = new { Name = "张三", Age = 20, result, Data = JsonSerializer.Serialize(jsonStr) };
            return new JsonResult(data);
        }

        [HttpPut]
        public async Task<IActionResult> Put()
        {
            var jsonStr = Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)],
                CurrentTime = DateTime.Now
            })
            .ToArray();
            //post请求
            var reqJson = new StringContent(JsonSerializer.Serialize(jsonStr), Encoding.UTF8, Application.Json);
            var httpClient = _httpClientFactory.CreateClient();
            using var httpResponseMessage = await httpClient.PostAsync("http://localhost:5249/WeatherForecast",reqJson);
            var result = await httpResponseMessage.Content.ReadAsStringAsync();

            var data = new { Name = "张三", Age = 20, result, Data = JsonSerializer.Serialize(jsonStr) };
            return new JsonResult(data);
        }
    }
}
